package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.api.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotNewsService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.ApArticleConScore;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.channels.Channel;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HotNewsServiceImpl implements HotNewsService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @XxlJob("hotNewsSchedduleRefresh")
    @Override
    public void hotNewsSchedduleRefresh() {
         log.info("开始执行定时任务");
        // 1.查询文章列表5天内
        Date date = DateTime.now().minusDays(5).toDate();
        List<ApArticle> apArticles5Days = apArticleMapper.loadArticleListByLatest5Day(date);
        // 2.更新文章的分值
        ApArticleConScore apArticleConScore = new ApArticleConScore();
        List<ApArticleConScore> articleScoreList = getArticleScoreList(apArticles5Days);
        //3.区分频道并加入缓存
        addArticleToRedisDistinctChannel(articleScoreList);

        //4加入定时任务
        log.info("结束执行定时任务");



    }

    @Autowired
    private IWemediaClient wemediaClient;
    private void addArticleToRedisDistinctChannel(List<ApArticleConScore> articleScoreList) {
        ResponseResult channels = wemediaClient.getChannels();
        log.info("查询频道：{}",channels);
        log.info("查询数据库文章：{}",articleScoreList);
        if(channels.getCode().equals(200)){
            List<WmChannel> wmChannels = JSON.parseArray(JSON.toJSONString(channels.getData()), WmChannel.class);
            for (WmChannel wmChannel : wmChannels) {
                log.info("开始处理频道：{}",wmChannel.getName());
                log.info("开始处理id：{}",wmChannel.getId());
                List<ApArticleConScore> collectByChannel = articleScoreList.stream()
                        .filter(articleScore -> articleScore.getChannelId().equals(wmChannel.getId()))
                        .sorted(Comparator.comparing(ApArticleConScore::getScore).reversed())
                        .collect(Collectors.toList());
                log.info("频道：{}",wmChannel.getName());
                log.info("频道里的文章：{}",collectByChannel);
                //加入缓存
                addCache(collectByChannel,ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId());
                log.info("频道加入redis：{}",wmChannel.getName());
                log.info("频道文章：{}",collectByChannel);
            }
        }
        List<ApArticleConScore> collectAll = articleScoreList.stream()
                .sorted(Comparator.comparing(ApArticleConScore::getScore).reversed())
                .collect(Collectors.toList());
        addCache(collectAll,ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
        log.info("首页热点文章加入redis：{}",collectAll);
    }

    @Autowired
    private CacheService cacheService;
    private void addCache(List<ApArticleConScore> collectByChannel, String key) {
        List<ApArticleConScore> articlesToCache = collectByChannel;
        if (collectByChannel != null && collectByChannel.size() > 30){
            articlesToCache = collectByChannel.subList(0, 30); // 使用截取后的结果
        }
        String jsonString = JSON.toJSONString(articlesToCache);
        cacheService.set(key, jsonString);
    }

    private List<ApArticleConScore> getArticleScoreList(List<ApArticle> apArticles5Days) {

        List<ApArticleConScore> collect = apArticles5Days.stream()
                .map(apArticle -> {
                    ApArticleConScore apArticleConScore = getApArticleConScore(apArticle);

                    return apArticleConScore;
                })
                .collect(Collectors.toList());

         log.info("文章带分数结束：{}",collect);

        return collect;
    }

    //获取单篇 包含分数score的文章对象：ApArticleConScore
    public static ApArticleConScore getApArticleConScore(ApArticle apArticle) {
        ApArticleConScore apArticleConScore = new ApArticleConScore(); // 每次创建新对象
        BeanUtils.copyProperties(apArticle, apArticleConScore);
        if (apArticleConScore.getChannelId() == null){
            apArticleConScore.setChannelId(ArticleConstants.DEFAULT_SINGLE_TAG);
        }
        log.info("文章带分数：{}",apArticleConScore);
        log.info("文章：{}", apArticle);
        Integer score = 0;
        if (apArticle.getViews() != null) {
            score += apArticle.getViews() * ArticleConstants.HOT_ARTICLE_SCORE_WEIGHT_view;
        }
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_SCORE_WEIGHT_like;
        }
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_SCORE_WEIGHT_comment;
        }
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_SCORE_WEIGHT_collection;
        }
        apArticleConScore.setScore(score);
        log.info("文章带分数：{}",apArticleConScore);
        return apArticleConScore;
    }
}
